# Windows 系统运维监控脚本  

# 定义函数来检查 CPU 使用率  
function CheckCpuUsage {  
    $cpu = Get-WmiObject -Class Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average  
    Write-Host "CPU 使用率: $($cpu.Average)%"  
    if ($cpu.Average -gt 80) {  
        Write-Warning "CPU 使用率过高！"  
    }  
}  

# 定义函数来检查内存使用情况  
function CheckMemoryUsage {  
    $memory = Get-WmiObject -Class Win32_OperatingSystem | Select-Object FreePhysicalMemory, TotalVisibleMemorySize  
    $freeMemory = $memory.FreePhysicalMemory / 1MB  
    $totalMemory = $memory.TotalVisibleMemorySize / 1MB  
    $usedMemory = $totalMemory - $freeMemory  
    $memoryUsage = ($usedMemory / $totalMemory) * 100  

    Write-Host "内存使用情况: $($memoryUsage.ToString("F2"))%"  
    if ($memoryUsage -gt 80) {  
        Write-Warning "内存使用率过高！"  
    }  
}

# 定义函数来检查磁盘空间  
# function CheckDiskSpace {
#     Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3} | ForEach-Object {
#         $freeSpace = ($_.FreeSpace / $_.Size) * 100
#         Write-Host "$($_.Name) 剩余空间: $($freeSpace.ToString("F2"))%"
#         if ($freeSpace -lt 20) {
#             Write-Warning "$($_.Name) 磁盘空间不足！"
#         }
#     }  # 这里闭合 ForEach-Object 的大括号
# }  # 这里闭合函数的定义


# 定义函数来检查服务状态  
function CheckServiceStatus {  
    $criticalServices = @("Spooler", "Dhcp", "W32Time")  # 示例关键服务  
    foreach ($service in $criticalServices) {  
        $svc = Get-Service -Name $service  
        Write-Host "$($svc.Name) 服务状态: $($svc.Status)"  
        if ($svc.Status -ne "Running") {  
            Write-Warning "$($svc.Name) 服务未运行！"  
        }  
    }  
}  

# 执行监控函数  
CheckCpuUsage  
CheckMemoryUsage  
# CheckDiskSpace  
CheckServiceStatus  

# 你可以根据需要添加更多的监控项，比如网络活动、安全日志检查等  

# 脚本结束  
# Write-Host "系统运维监控完成。"